package com.weiaibenpao.demo.chislim.ui.activity.discover;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.base.BaseActivity;
import com.weiaibenpao.demo.chislim.utils.Constant;
import com.weiaibenpao.demo.chislim.utils.LoadingDialogUtils;
import com.weiaibenpao.demo.chislim.utils.Utils;

import java.io.File;

import butterknife.BindView;


public class WebViewActivity extends BaseActivity {

    @BindView(R.id.mid_text)
    TextView myTitle;
    @BindView(R.id.left_image)
    ImageView leftImg;
    private String urlStr; // 网络路径
    private String urlTitle; //标题


    private static final String APP_CACHE_DIRNAME = "/webcache";

    @BindView(R.id.webView)
    WebView mWebView;
    private LoadingDialogUtils.Builder builder;
    private int type;


    @Override
    public int setLayoutResourceID() {
        return R.layout.activity_web_view;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        urlStr = getIntent().getStringExtra(Constant.WEB_URL);
        urlTitle = getIntent().getStringExtra(Constant.MARATHON_TITLE);
        type = getIntent().getIntExtra(Constant.TYPE, 1);
        //  titleStr = getIntent().getStringExtra("title");
        /*if (titleStr != null) {
            tv_title.setText(titleStr);
        } else {
            tv_title.setText("活动");
        }*/

        leftImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        myTitle.setText(urlTitle);
//        if (type==0){
//
//        }
            initWebView();

    }

    public static void startSelf(Context context, String contentUrl, String titleName,int type) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra(Constant.WEB_URL, contentUrl);
        intent.putExtra(Constant.MARATHON_TITLE, titleName);
        intent.putExtra(Constant.TYPE,type);
        context.startActivity(intent);
    }

    private void initWebView() {
        //声明WebSettings子类
        WebSettings webSettings = mWebView.getSettings();
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口

        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);  //设置 缓存模式 LOAD_CACHE_ONLY
        if (Utils.isNetWorkConnected()) {
            webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);//根据cache-control决定是否从网络上取数据。
        } else {
            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//没网，则从本地获取，即离线加载
        }

        // 开启 DOM storage API 功能
        webSettings.setDomStorageEnabled(true);
        //开启 database storage API 功能
        webSettings.setDatabaseEnabled(true);
        String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACHE_DIRNAME;
//      String cacheDirPath = getCacheDir().getAbsolutePath()+Constant.APP_DB_DIRNAME;

        //设置数据库缓存路径
        webSettings.setDatabasePath(cacheDirPath);
        //设置  Application Caches 缓存目录
        webSettings.setAppCachePath(cacheDirPath);
        //开启 Application Caches 功能
        webSettings.setAppCacheEnabled(true);
        builder = new LoadingDialogUtils.Builder(this);
        builder.setTitle("正在加载...").show();
        //第二种加载进度条的方法
//        mWebView.setWebChromeClient(new WebChromeClient(){
//            @Override
//            public void onProgressChanged(WebView view, int newProgress) {
//
//                if (newProgress==100)
//                    dismissProgressDialog();
//                super.onProgressChanged(view, newProgress);
//            }
//        });

        mWebView.loadUrl(urlStr);

        //第一种加载进度条的方法
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                builder.dismiss();


                super.onPageFinished(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                if (type==0){
//                    view.loadUrl(url);
//                    return false;
//                }
                return false;
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                builder.dismiss();

                super.onReceivedError(view, request, error);
            }
        });

        mWebView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                myTitle.setText(title);
            }
        });


//        mWebView.loadUrl("https://www.baidu.com/");
//        Log.e("HWebView","load url is "+urlStr);

    }

    /**
     * 清除WebView缓存
     */
    public void clearWebViewCache() {
//清除网页访问留下的缓存
//由于内核缓存是全局的因此这个方法不仅仅针对webview而是针对整个应用程序.
        mWebView.clearCache(true);

//清除当前webview访问的历史记录
//只会webview访问历史记录里的所有记录除了当前访问记录
        mWebView.clearHistory();

//这个api仅仅清除自动完成填充的表单数据，并不会清除WebView存储到本地的数据
        mWebView.clearFormData();

        //清理Webview缓存数据库
        try {
            deleteDatabase("webview.db");
            deleteDatabase("webviewCache.db");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //WebView 缓存文件
        File appCacheDir = new File(getFilesDir().getAbsolutePath() + APP_CACHE_DIRNAME);

        File webviewCacheDir = new File(getCacheDir().getAbsolutePath() + "/webviewCache");

        //删除webview 缓存目录
        if (webviewCacheDir.exists()) {
            deleteFile(webviewCacheDir);
        }
        //删除webview 缓存 缓存目录
        if (appCacheDir.exists()) {
            deleteFile(appCacheDir);
        }
    }

    @Override
    protected void onDestroy() {
        clearWebViewCache();
        if (mWebView != null) {
            mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebView.clearHistory();

            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
            mWebView.destroy();
            mWebView = null;
        }

        super.onDestroy();

    }

    @Override
    protected void onPause() {
        super.onPause();
        //当页面被失去焦点被切换到后台不可见状态，需要执行onPause
        //通过onPause动作通知内核暂停所有的动作，比如DOM的解析、plugin的执行、JavaScript执行。
        mWebView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //激活WebView为活跃状态，能正常执行网页的响应
        mWebView.onResume();
    }

    /**
     * 递归删除 文件/文件夹
     *
     * @param file
     */
    public void deleteFile(File file) {


        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            file.delete();
        } else {

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();    //返回上一页
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
